#!/usr/bin/python
# -*- coding: utf-8 -*-

import pygtk
import sys
pygtk.require('2.0')
import gtk
import gtk.gdk as gdk
import gobject
import pango

reload(sys)
sys.setdefaultencoding('utf8')

class osd:
    def popup(self, text, font, bgcolor, fgcolor):
        self.layout = self.win.create_pango_layout('')
        self.layout.set_font_description(pango.FontDescription(font))
        self.layout.set_markup(text)
        self.layout.set_ellipsize(pango.ELLIPSIZE_NONE)
        self.layout.set_alignment(pango.ALIGN_CENTER)
        self.layout.set_justify(False)
        self.layout.set_width(gdk.screen_width()*pango.SCALE)

        width, height = self.layout.get_pixel_size()
        off_x = 2
        off_y = 2
        off_x -= gdk.screen_width()/2 - width/2

        self.darea.set_size_request(width, height)
        self.darea.realize()

        pixmap = gtk.gdk.Pixmap(self.darea.window, width, height)
        pixmap.set_colormap(self.darea.window.get_colormap())
        fg_gc = gdk.GC(pixmap); fg_gc.copy(self.darea.style.fg_gc[gtk.STATE_NORMAL])
        bg_gc = gdk.GC(pixmap); bg_gc.copy(self.darea.style.fg_gc[gtk.STATE_NORMAL])
        fg_gc.set_foreground(self.darea.get_colormap().alloc_color(fgcolor))
        bg_gc.set_background(self.darea.get_colormap().alloc_color(bgcolor))
        pixmap.draw_layout(fg_gc, off_x, off_y, self.layout)

        bitmap = gtk.gdk.Pixmap(self.darea.window, width, height, 1)
        bitmap.set_colormap(self.darea.window.get_colormap())

        fg_gc = gdk.GC(bitmap)
        bg_gc = gdk.GC(bitmap)
        fg_gc.set_foreground(gdk.Color(pixel=-1))
        bg_gc.set_background(gdk.Color(pixel=0))

        bitmap.draw_rectangle(bg_gc, True, 0, 0, width, height)
        bitmap.draw_layout(fg_gc, off_x, off_y, self.layout)

        self.darea.window.set_back_pixmap(pixmap, False)
        self.win.window.shape_combine_mask(bitmap, 0, 0)
        self.win.width = width
        self.win.height = height

        pixmap = gdk.Pixmap(None, width, height, 1)
        self.win.input_shape_combine_mask(pixmap, 0, 0)

    def move(self, x=None, y=None):
        if x==None and y==None:
            width, height = self.layout.get_pixel_size()
            self.win.move(gdk.screen_width()/2 - width/2, gdk.screen_height()/2 - height/2)

    def __init__(self, text, font, bgcolor, fgcolor):
        self.win = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.win.set_keep_below(True)
        self.win.set_type_hint(gtk.gdk.WINDOW_TYPE_HINT_DOCK)
        self.win.add_events(gtk.gdk.ENTER_NOTIFY_MASK)
        self.win.show()

        self.darea = gtk.DrawingArea()
        self.win.add(self.darea)
        self.darea.show()

        self.popup(text, font, bgcolor, fgcolor)

def main():
     gtk.main()
     return 0

if __name__ == "__main__":
    w = osd("<span weight='bold'>abcd魏安楠</span>",
            "sans serif 14",
            "#ffffff",
            "#000000")
    w.move()
    main()